<?php

namespace mszl\api\utils;


use Medoo\Medoo;
use mszl\api\conf\MysqlConf;
use mszl\api\traits\DynamicParamsSingleton;
use PDOStatement;

/**
 * @method static mixed get($join = null, $columns = null, $where = null)
 * @method static int count($where = null)
 * @method static mixed select($columns, $where)
 * @method static bool has($join, $where = null)
 * @method static string max($join, $column = null, $where = null)
 * @method static string min($join, $column = null, $where = null)
 * @method static string sum($join, $column = null, $where = null)
 * @method static string avg($join, $column = null, $where = null)
 * @method static array rand($join, $column = null, $where = null)
 * @method static void action(callable $actions)
 * @method static string id(string $name = null)
 * @method static array log()
 * @method static string last()
 * @method static null|PDOStatement insert(array $values)
 * @method static null|PDOStatement update(array $data, array $where = null)
 */
class DbMySQL
{
    protected ?Medoo $db = null;
    protected static string $table = '';
    protected static string $configFile = 'db';
    protected static string $configFileSection = 'basic';

    const IGNORE_METHOD = ['action'];

    protected static array $map = [];

    use DynamicParamsSingleton;

    public function __construct(MysqlConf $conf)
    {
        $this->db = new Medoo([
            'database_type' => 'mysql',
            'database_name' => $conf->database,
            'server' => $conf->host,
            'username' => $conf->user,
            'password' => $conf->password,
            'port' => $conf->port,
        ]);
    }

    private function test(array $data): void
    {
        $this->db->insert('test', $data);
        $this->db->update('test', $data);
        $this->db->id();
    }



    public static function __callStatic($method, $args)
    {
        //读取配置文件
        $conf = IniReader::getInstance(static::$configFile, static::$configFileSection)->get();
        $mysqlConf = MysqlConf::get($conf);
        $instance = self::getInstance($mysqlConf);
        if (!in_array($method, static::IGNORE_METHOD)) {
            array_unshift($args, static::getTableName());
        }
        return call_user_func_array([
            $instance->db,
            $method
        ], $args);
    }

    public static function getTableName(): string
    {
        $tableName = static::$table;
        if (isset($map[static::class])) return $map[static::class];
        if (empty($tableName)) {
            $fullName = (new \ReflectionClass(static::class))->getShortName();
            $tableName = substr($fullName, 0, -5);
            $tableName = uncamelize($tableName);
        }
        $map[static::class] = $tableName;
        return $tableName;
    }
}